import BannerPng from "@/assets/images/banner.png";
import SearchPng from "@/assets/images/search.png";
import { useEffect, useRef, useState } from "react";
import echarts from "@/echarts/index";
import { post } from "@/request/index";
import { useNavigate } from "react-router";
import { Select } from "antd";

export default function Home() {
  const barChartRef = useRef<HTMLDivElement>(null);
  const pieChartRef1 = useRef<HTMLDivElement>(null);
  const pieChartRef2 = useRef<HTMLDivElement>(null);
  let chart: any;
  let chart1: any;
  let chart2: any;
  const [typeList, setTypeList] = useState<any[]>([]);
  const navigate = useNavigate();
  const [keyword, setKeyword] = useState("");
  const baseURL = import.meta.env.VITE_BASE_URL;
  const [options, setOptions] = useState<any>([]);
  const [value, setValue] = useState("");

  const initEcharts = (values: any[]) => {
    chart = echarts.init(barChartRef.current);
    chart.setOption({
      xAxis: {
        type: "category",
        data: values.map((item) => item.speciesName),
        axisLabel: {
          interval: 0,
          rotate: 20,
        },
      },
      grid: {
        right: 0,
        left: "10%",
      },
      yAxis: {
        type: "value",
      },
      series: [
        {
          data: values.map((item) => item.allNumber),
          type: "bar",
          label: {
            show: true,
            position: "top",
          },
          itemStyle: {
            // 使用方法一的写法
            color: new echarts.graphic.LinearGradient(0, 1, 1, 0, [
              { offset: 0, color: "#f3b255" },
              { offset: 1, color: "#eb7833" },
            ]),
          },
        },
      ],
    });
  };

  const initPieChart1 = (data: any[]) => {
    chart1 = echarts.init(pieChartRef1.current);
    chart1.setOption({
      tooltip: {
        trigger: "item",
      },
      series: [
        {
          name: "number of sequences",
          type: "pie",
          radius: "80%",
          data: data.map((item: any) => ({ value: item.mutantCount, name: item.commentaryMutant })),
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: "rgba(0, 0, 0, 0.5)",
            },
          },
        },
        {
          name: "number of sequences",
          type: "pie",
          radius: "80%",
          data: data.map((item: any) => ({ value: item.mutantCount, name: item.commentaryMutant })),
          label: {
            normal: {
              show: true,
              position: "inner", // 数值显示在内部
              formatter: "{c}", // 格式化数值百分比输出
            },
          },
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: "rgba(0, 0, 0, 0.5)",
            },
          },
        },
      ],
    });
  };
  const initPieChart2 = (data: any) => {
    chart2 = echarts.init(pieChartRef2.current);
    chart2.setOption({
      tooltip: {
        trigger: "item",
      },
      series: [
        {
          name: "number of kinetics data",
          type: "pie",
          radius: "80%",
          data: data.map((item: any) => ({ value: item[1], name: item[0] === "kcatKm" ? "kcat/Km" : item[0] })),
        },
        {
          name: "number of kinetics data",
          type: "pie",
          radius: "80%",
          data: data.map((item: any) => ({ value: item[1], name: item[0] === "kcatKm" ? "kcat/Km" : item[0] })),
          label: {
            normal: {
              show: true,
              position: "inner", // 数值显示在内部
              formatter: "{c}", // 格式化数值百分比输出
            },
          },
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: "rgba(0, 0, 0, 0.5)",
            },
          },
        },
      ],
    });
  };

  const resizeEcharts = () => {
    chart && chart.resize();
    chart1 && chart1.resize();
    chart2 && chart2.resize();
  };

  const initAddEventListeren = () => {
    window.addEventListener("resize", resizeEcharts);
  };

  const getAllTypeList = () => {
    post("/function/getAllType", { params: {} }).then((res: any) => {
      setTypeList([...res.vos]);
      initEcharts([...res.vos]);
    });
  };

  const getPieChartData = () => {
    post("/function/getMutationDataList").then((res: any[]) => {
      initPieChart1(res || []);
    });
    post("/function/getFourDataList").then((res: any[]) => {
      let entires = Object.entries(res);
      initPieChart2(entires || []);
    });
  };

  const gotoSearchPage = (name: string) => {
    navigate(`/search?name=${name}&isSpecies=${1}`);
  };

  const searchInput = () => {
    navigate(`/search?name=${keyword}&value=${value}`);
  };

  const handleChange = (value: string) => {
    console.log(value);
    setValue(value);
    if (value == "1") {
      setKeyword("Hammerhead");
    }
    if (value == "5") {
      setKeyword("1911762");
    }
    if (value == "6") {
      setKeyword("GGGCCGAAACGUA");
    }
  };

  const getOptions = () => {
    post("/function/getHomeRibozymeSearchType").then((res: any) => {
      setValue(res[0].id);
      setKeyword("Hammerhead");
      setOptions([...res].map((item) => ({ value: item.id, label: item.fieldName })));
    });
  };

  useEffect(() => {
    initAddEventListeren();
    getAllTypeList();
    getPieChartData();
    getOptions();
    return () => {
      window.removeEventListener("resize", resizeEcharts);
    };
  }, []);
  return (
    <div>
      <img src={BannerPng} style={{ width: "100%" }} />

      <div
        style={{
          position: "relative",
          maxWidth: "1200px",
          top: "-100px",
          margin: "0 auto",
        }}
        className="homeBox"
      >
        <div style={{ background: "#fff", textAlign: "left", padding: "20px" }}>
          The RKD collects experimentally validated ribozyme kinetic data extracted from literatures. It stores kinetic
          data of kobs, kcat, Km, kcat/Km, chemical reaction conditions (temperature, pH, metal ion), sequences and
          dot-bracket encodings of ribozymes and substrates, graphical 2D views of ribozymes and/or substrates, and
          mutation information of ribozymes and substrates.
        </div>

        <div style={{ background: "#fff", margin: "20px 0", padding: "20px" }}>
          <div style={{ fontSize: "20px", fontWeight: "700" }}>Ribozyme species</div>
          <div style={{ color: "#555" }}>Click on one of the options below to see the list of entries.</div>
          <div
            style={{
              marginTop: "40px",
              display: "grid",
              gridTemplateColumns: "repeat(auto-fill, 160px)",
              gap: "70px",
              justifyContent: "center",
            }}
            className="species"
          >
            {typeList.map((item, index) => {
              return (
                <div key={index} style={{ cursor: "pointer" }} onClick={() => gotoSearchPage(item.speciesName)}>
                  <div key={item.id} style={{ position: "relative", width: "100%" }}>
                    <img
                      src={baseURL + item.speciesImage}
                      alt=""
                      style={{
                        width: "160px",
                        height: "160px",
                        borderRadius: "50%",
                        boxShadow: "rgba(99, 99, 99, 0.2) 0px 2px 8px 0px",
                        marginBottom: "10px",
                      }}
                      className="navImag"
                    />
                  </div>
                  <div
                    style={{
                      fontWeight: "700",
                      textAlign: "center",
                    }}
                  >
                    {item.speciesName === "Others" ? "" : item.speciesName}
                  </div>
                </div>
              );
            })}
          </div>
        </div>
        <div style={{ background: "#fff", textAlign: "center", padding: "20px" }}>
          <div style={{ fontSize: "20px", fontWeight: "700" }}>Quick database search</div>
          <div style={{ color: "#555" }}>
            Enter keywords (e.g. Ribozyme, Ribozyme sequence, Pubmed Id) to query the corresponding kinetic data
          </div>
          <div
            className="search1"
            style={{
              display: "flex",
              alignItems: "center",
              maxWidth: "1000px",
              marginTop: "20px",
              justifyContent: "center",
              margin: "20px auto 0 auto",
            }}
          >
            <div
              style={{
                flex: "1",
                borderRadius: "40px",
                border: "1px solid #5ea1f7",
                padding: "15px",
                display: "flex",
                alignItems: "center",
                gap: "20px",
                height: "50px",
                boxSizing: "border-box",
              }}
            >
              <div style={{ borderRight: "1px solid #000", paddingRight: "20px" }}>
                <Select
                  value={value}
                  style={{ width: "20vw", maxWidth: "200px" }}
                  options={options}
                  onChange={handleChange}
                />
              </div>
              <div style={{ flex: "1" }}>
                <input
                  value={keyword || ""}
                  style={{ width: "100%", height: "30px", border: "none", outline: "none" }}
                  type="text"
                  placeholder="Enter any string of …"
                  onChange={(e) => setKeyword(e.target.value)}
                />
              </div>
            </div>
            <div
              style={{
                display: "flex",
                alignItems: "center",
                background: "linear-gradient(90deg, #0078f9, #56b8fb)",
                padding: "0 20px",
                gap: "5px",
                color: "#fff",
                borderRadius: "30px",
                marginLeft: "-60px",
                cursor: "pointer",
                height: "50px",
              }}
              onClick={searchInput}
            >
              <img src={SearchPng} alt="" />
              <div className="searchText">Search</div>
            </div>
          </div>
          {/* <div style={{ display: "flex", justifyContent: "center", marginTop: "30px" }}>
            <input
              style={{
                width: "400px",
                height: "50px",
                borderRadius: "40px",
                border: "1px solid #5ea1f7",
                outline: "none",
                padding: "0 80px 0 20px",
              }}
              type="text"
              placeholder="Hammerhead,15703231"
              onChange={(e) => setKeyword(e.target.value)}
            />
            <div
              style={{
                display: "flex",
                alignItems: "center",
                padding: "0 20px",
                gap: "5px",
                color: "#fff",
                borderRadius: "30px",
                marginLeft: "-60px",
                cursor: "pointer",
                background: "linear-gradient(90deg, #0078f9, #56b8fb)",
              }}
              onClick={() => searchInput()}
            >
              <img src={SearchPng} alt="" />
              <div>Search</div>
            </div>
          </div> */}
        </div>
        <div
          style={{ display: "flex", alignItems: "center", background: "#fff", padding: "20px", marginTop: "20px" }}
          className="number"
        >
          <div style={{ flex: 1 }}>
            <div style={{ fontWeight: 700, fontSize: "18px", marginBottom: "10px" }}>Number of sequences</div>
            <div style={{ width: "100%", height: "400px" }} ref={pieChartRef1}></div>
          </div>
          <div style={{ flex: 1 }}>
            <div style={{ fontWeight: 700, fontSize: "18px", marginBottom: "10px" }}>Number of kinetics data</div>
            <div style={{ width: "100%", height: "400px" }} ref={pieChartRef2}></div>
          </div>
        </div>
        <div style={{ background: "#fff", marginTop: "20px", padding: "20px" }}>
          <div style={{ fontSize: "20px", fontWeight: "700" }}>Update log</div>
          <div className="update" style={{ marginTop: "40px" }}>
            <div style={{ fontWeight: 700, fontSize: "18px", marginBottom: "10px" }}>
              Recent update: {new Date().toLocaleDateString()}
            </div>
            <div style={{ flex: "2", height: "600px" }}>
              <div style={{ width: "100%", height: "600px" }} ref={barChartRef}></div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
